<template>
  <div>
    <el-card>
      <el-col :span="8">
        <el-input v-model="chaBookId" clearable></el-input>
      </el-col>
      <el-col :span="4">
        <el-button @click="chaThisBook">查询</el-button>
      </el-col>
      <el-table :data="bookForm" border style="width: 100%" stripe>
        <el-table-column prop="_id" label="书籍ID" width="230">
          <template slot-scope="scope">
            <h4 @click="toBook(scope.row._id)">{{scope.row._id}}</h4>   
          </template>
        </el-table-column>
        <el-table-column prop="bookname" label="书名" width="170">
        </el-table-column>
        <el-table-column prop="sort" label="分类" width="80">
        </el-table-column>
        <el-table-column prop="writerid" label="作者id" width="230">
          <template slot-scope="scope">
            <h4 @click="toWriter(scope.row.writerid)">{{scope.row.writerid}}</h4> 
            <span>{{scope.row.writername}}</span>  
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="180">
          <template slot-scope="scope">
            <el-button type="danger" plain v-if="scope.row.state == '1'"
            @click="isTrue(scope.row._id)">封禁中,点击解禁</el-button
            >
            <el-button type="success" plain v-if="scope.row.state == '0'"
            @click="isFalse(scope.row._id)">正常，点击封禁</el-button
            >
          </template>
        </el-table-column>
                <el-table-column prop="state" label="状态" width="120">
          <template slot-scope="scope">
            <el-button type="danger" plain v-if="scope.row.isend == '1'"
            >完结</el-button
            >
            <el-button type="success" plain v-if="scope.row.isend == '0'"
            >连载中</el-button
            >
          </template>
        </el-table-column>
         <el-table-column prop="size" label="字数" width="120">
        </el-table-column>
        <el-table-column prop="date" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="120"> 
            <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="medium" @click="changeThisBook(scope.row._id)">修改</el-button>
                <!-- <el-button type="primary" icon="el-icon-message" size="medium">发送信息</el-button> -->
                <!-- <el-button type="primary" icon="el-icon-delete" size="medium" @click="deleteThisBook(scope.row._id)">删除</el-button> -->
            </template>
        </el-table-column>
      </el-table>
    <!-- 分页 -->
    <div class="block">
    <span class="demonstration">共有{{isLength}}条记录</span>
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage"
      layout="prev, pager, next, jumper"
      :page-size="10"
      :total="isLength">
    </el-pagination>
    </div>
    </el-card>
      <!-- 修改书籍信息对话框 -->
    <el-dialog title="修改" :visible.sync="changeBookDialogVisible" width="50%">
      <div class="changePic">
        <img :src="this.thisBook.avatar" class="gaiImage" />
        <el-upload
          class="upload-demo"
          ref="upload"
          action="http://127.0.0.1:3000/api/bookAva/"
          :auto-upload="false"
          :on-remove="onRemove"
          :on-change="onChange"
          :before-upload="beforeUpload"
          :on-success = 'onSuccess'
          list-type="picture"
          name="pic"
          accept="image/jpg, image/jpeg, image/png"
        >
          <el-button size="small" type="primary" id="wei" >选取文件</el-button>
          <el-button size="small" type="success" @click="submitUpload" id="yi">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload>
      </div>
      <el-form ref="gaiFormRef" :model="thisBook" label-width="80px">
        <el-form-item label="书名" prop="bookname">
          <el-input v-model="thisBook.bookname"></el-input>
        </el-form-item>
        <el-form-item label="书籍编号" prop="id">
          <el-input v-model="thisBook._id" disabled></el-input>
        </el-form-item>
        <el-form-item label="书籍分类" prop="sort">
          <el-input v-model="thisBook.sort" disabled></el-input>
        </el-form-item>
        <el-form-item label="书籍简介" prop="explain">
          <el-input v-model="thisBook.explain"></el-input>
        </el-form-item>
        <el-form-item label="创建时间" prop="date">
          <el-input v-model="thisBook.date" disabled></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeBookDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subThisChange(thisBook._id)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import {isID} from '../../assets/js/id-name'
export default {
  created() {
    this.getBookList();
  },
  data() {
    return {
      chaBookId:"",
      bookForm: [
        {
        date:'',
        _id: "",
        bookname: "",
        state: "",
        writerid:'',
        sort:[],
        writername:"",
        }
      ],
      isLength:0,
      currentPage: 1,
      pageSize:10,
      thisBook: {},
      changeBookDialogVisible:false,
    };
  },
  methods: {
    async getBookList() {
      const { data: res } = await this.$http.post("/books/showBook",{pageSize:this.pageSize,currentPage:this.currentPage});
      //console.log(res);
      this.bookForm = res.data;
      this.isLength = res.num;
      //console.log(this.bookForm.writerid);
    },
    async isTrue(id){
        let state = 0;
        const {data:res} = await this.$http.post(`/books/updateState/${id}`,{state})
        if(res.status != 200) return this.$message.error("error")
        this.$message.success("success");
        this.getBookList();
    },
    async isFalse(id){
        let state = 1;
        const {data:res} = await this.$http.post(`/books/updateState/${id}`,{state})
        if(res.status != 200) return this.$message.error("error")
        this.$message.success("success");
         this.getBookList();
    },
    toBook(id){
      let routeUrl = this.$router.resolve(`/tobook/${id}`);
      window.open(routeUrl.href, "_blank");
    },
    toWriter(id){
      let routeUrl = this.$router.resolve(`/toWriter/${id}`);
      window.open(routeUrl.href, "_blank");
    },
    handleCurrentChange(val){
        this.currentPage = val;
        this.getBookList();
    },
    async chaThisBook(){
      let n = isID(this.chaBookId)
      //alert(n)
      if(n == null){
        this.getBookList();
        return;
      } else if(n == 'isId'){
        const {data:res} = await this.$http.get(`/books/thisbookA/${this.chaBookId}`)
        this.bookForm =  [
        {
        date:'',
        _id: "",
        bookname: "",
        state: "",
        writerid:'',
        sort:[],
        writername:"",
        }
      ]
      //this.bookForm = res.data;
        this.isLength = 1;
        this.bookForm[0]._id = res.data._id;
        this.bookForm[0].date = res.data.date
        this.bookForm[0].bookname = res.data.bookname 
        this.bookForm[0].state = res.data.state
        this.bookForm[0].writerid = res.data.writerid
        this.bookForm[0].sort = res.data.sort
        this.bookForm[0].writername = res.data.writername
        return;
      } else if(n == 'isName'){
        const { data: res } = await this.$http.get(`/books/thisbookB`, {
        params: { bookname: this.chaBookId,        
        pageSize: this.pageSize,
        currentPage: this.currentPage, },
      });
      if (res.data == "") {
        this.$message.error("查无此书")
      } else {
        this.bookForm = res.data;
        this.isLength = res.num;
      }
      } else if(n == 'false'){
        this.$message.error("请输入正确的书籍id")
        return;
    }
    },
    deleteThisBook(id){
      this.$confirm('此操作将永久删除此书, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data:res} = await this.$http.delete(`/books/delete/${id}`);
          if(res.status == 200){
            this.getBookList();
            this.$message({
            type: 'success',
            message: '删除成功!'
          });
          } else {
            this.$message.error("删除失败")
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    async changeThisBook(id){
      this.changeBookDialogVisible = true;
      const { data: res } = await this.$http.get(`books/thisbookW/${id}`);
      this.thisBook= res.data;
    },
    async subThisChange(id){
      //console.log(id);
      const { data: res } = await this.$http.post(`books/changeBook/${id}`, {
        bookname: this.thisBook.bookname,
        explain: this.thisBook.explain,
      });
      if (res.status === 200) {
        this.$message.success("更改成功");
        this.changeBookDialogVisible = false;
        if(this.chaBookId == ''){
          this.getBookList();
          return
        } else {
          this.chaThisBook();
        }
      }
    },
    onChange(){
      document.getElementById("wei").style.display = 'none'
      document.getElementById("yi").style.display = 'inline'
    },
    onRemove(){
      document.getElementById("wei").style.display = 'inline'
      document.getElementById("yi").style.display = 'none'
    },
    beforeUpload(file){
      const isLt2M = file.size / 1024 < 500;
      if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
          return false;
        }
    },
    submitUpload() {
      this.$refs.upload.submit();
      },
    onSuccess(res){
        let url = `http://127.0.0.1:3000/uploads/book/${res.file.filename}`
        this.afterSuccess(url)
        //const{data:res} = await this.$http.post(`books/changeBookPic/${this.thisBookId}`,{url:url})
      },
    async afterSuccess(url){
      const{data:res} = await this.$http.post(`books/changeBookPic/${this.thisBook._id}`,{url:url})
      console.log(res);
      if(res === 'OK'){
        this.changeBookDialogVisible = false;
        this.$refs.upload.clearFiles();
        this.getBookList();
        document.getElementById("wei").style.display = 'inline'
        document.getElementById("yi").style.display = 'none'
      }
    }, 
  }
};
</script>
<style lang="less" scoped>
h4:hover{
  color: blue;
  cursor:pointer
}
.gaiImage {
  //修改中封面样式
  margin: 15px;
  height: 160px;
  width: 120px;
}
</style>
